package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.example.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private final static Long VALID_TIME = 60 * 1000L;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        // 记录时间
        long start = System.currentTimeMillis();
        // 不进行缓存
        response.setHeader("Progma","No-cahce");
        try {
            // 生成验证码
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            String code = captcha.getCode();
            session.setAttribute(captchaProperties.getSession().getKey(),code);
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("getCaptcha 花费时间：" + (end - start) + "ms");
    }
    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        // 验证验证码
        String code = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date date = (Date) session.getAttribute(captchaProperties.getSession().getDate());
//        if(captcha.equalsIgnoreCase(code) && System.currentTimeMillis() - date.getTime() < VALID_TIME){
//            return true;
//        }
        // 时间为空的时候也不行，这个是按照需求定的
        if(captcha.equalsIgnoreCase(code) && date != null && System.currentTimeMillis() - date.getTime() < VALID_TIME){
            return true;
        }
        return false;
    }
}
